package com.example.goodsmanagementcabinet.framents;

import android.app.DialogFragment;
import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.example.goodsmanagementcabinet.R;
import com.example.goodsmanagementcabinet.adapter.CheckKeyAdapter;
import com.example.goodsmanagementcabinet.adapter.KeyAdapter;
import com.example.goodsmanagementcabinet.base.BaseDialogFragment;
import com.example.goodsmanagementcabinet.base.GoodBoxManagerApp_;
import com.example.goodsmanagementcabinet.bean.KeyBean;
import com.example.goodsmanagementcabinet.db.DatabaseManager;
import com.example.goodsmanagementcabinet.otto.OttoManager;
import com.example.goodsmanagementcabinet.otto.OttoMsg;
import com.example.goodsmanagementcabinet.serialport.LockStateSerialPortConnect;
import com.example.goodsmanagementcabinet.serialport.SerialPortConnect;
import com.example.goodsmanagementcabinet.speaker.Speaker_;
import com.squareup.otto.Subscribe;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EBean;
import org.androidannotations.annotations.UiThread;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;


@EBean
public class AcapterFrament extends BaseDialogFragment {
    List<KeyBean> listKeys = new ArrayList<>();
    List<KeyBean> openKeys = new ArrayList<>();
    List<Integer> keylock = new ArrayList<>();
    LayoutInflater minflater;
    boolean isFinish = false;
    boolean isDoing = false;
    long outTime;
    LinearLayout mAppcetBtn, mCancleBtn;
    ImageView toHome;
    GridView keyGridVew;
    CheckKeyAdapter keyAdapter;
    CountDownTimer timer;
    Context context;
    boolean success = false;
    KeyBean myKey = null;

    public AcapterFrament() {

    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Holo_Light_Dialog_NoActionBar);

    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        this.getDialog().getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        this.getDialog().setCancelable(false);
        this.getDialog().setCanceledOnTouchOutside(false);
    }

    public void onResume() {
        super.onResume();
        this.getDialog().getWindow().setLayout(800, 1280);
    }

    @Subscribe
    @Background
    public void handlerOtto(OttoMsg msg) {
        if (TextUtils.equals(OttoMsg.OTTO_CHECK_KEY, msg.which)) {
            KeyBean key = (KeyBean) msg.data;
            if (openKeys.size() > 0) {
                for (KeyBean mykey : openKeys) {
                    if (TextUtils.equals(mykey.getKeyName(), key.getKeyName())) {
                        break;
                    }
                }
                openKeys.add(key);
            } else {
                openKeys.add(key);
            }
        } else if (TextUtils.equals(OttoMsg.OTTO_REMOVE_CHECK_KEY, msg.which)) {
            KeyBean key = (KeyBean) msg.data;
            Iterator<KeyBean> it = openKeys.iterator();
            while (it.hasNext()) {
                KeyBean keys = (KeyBean) it.next();
                if (key.getKeyName().equals(keys.getKeyName())) {
                    it.remove();
                }
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        minflater = inflater;
        final View view = inflater.inflate(R.layout.operating_fragment, container);
        openKeys.clear();
        Bundle args = getArguments();
        List<KeyBean> keyList = (List<KeyBean>) args.getSerializable("KeyList");
        context = view.getContext();
        mAppcetBtn = view.findViewById(R.id.btnBrrowKey);
        mCancleBtn = view.findViewById(R.id.btnCanael);
        keyGridVew = view.findViewById(R.id.keyGridVew);
        toHome = view.findViewById(R.id.toHome);
        keyAdapter = new CheckKeyAdapter(view.getContext());
        keyGridVew.setAdapter(keyAdapter);
        keyAdapter.notifyRefresh(keyList);
        toHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hidiDialog();
//                OttoManager.getInstance().deliverMsg(OttoMsg.OTTO_TO_HOME, null);
            }
        });
        mAppcetBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (openKeys.size() <= 0) {
                    speak("请选择钥匙");
                } else {
                    Log.e("AcpterFrament", "openkey size " + openKeys.size());
                    outTime = System.currentTimeMillis();
                    setEnable(false);
                    mlock();
                }
            }
        });
        mCancleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (timer != null) {
                    timer.cancel();
                }
                mCancleBtn.setEnabled(true);
                success = false;
                setEnable(true);
                hidiDialog();
//                OttoManager.getInstance().deliverMsg(OttoMsg.OTTO_TO_HOME, null);
            }
        });
        return view;
    }

    @UiThread
    public void setEnable(boolean b) {
        keyAdapter.changeAllItem(b);
        mAppcetBtn.setEnabled(b);
    }

    public void mlock() {
        myKey = openKeys.get(0);
        if (myKey == null) {
            speak("钥匙信息为空");
            return;
        }
        SerialPortConnect.getInstance().readCode(Integer.parseInt(myKey.getLocation()));
        System.out.println("XXXXXXXXXXXx:" + (System.currentTimeMillis() - outTime));
        if (System.currentTimeMillis() - outTime > 60 * 1000) {
            isFinish = false;
            if (timer != null) {
                timer.cancel();
            }
            speak("操作超时");
            success = false;
            setEnable(true);
            hidiDialog();
            return;
        }
        if (isFinish) {
            if (timer != null) {
                timer.cancel();
            }
            speak("操作超时");
            success = false;
            setEnable(true);
            hidiDialog();
            return;
        }
        timer = new CountDownTimer(2000, 2000) {
            public void onTick(long millisUntilFinished) {
            }

            public void onFinish() {
                String keycodes = SerialPortConnect.getInstance().getKeyCode(Integer.parseInt(myKey.getLocation()) - 1);
                if (TextUtils.equals(keycodes, myKey.getKeyCode())) {
                    success = true;
                } else {
                    success = false;
                }
                String mlockState = SerialPortConnect.getInstance().getlockState(Integer.parseInt(myKey.getLocation()) - 1);
                if (TextUtils.equals(mlockState, "00") || TextUtils.equals(mlockState, "01")) {
                    if (!success) {
                        SerialPortConnect.getInstance().openLock(Integer.parseInt(myKey.getLocation()));
                        if (keycodes.equals("00000000")) {
                            speak("请放入钥匙");
                        } else {
                            speak("请放入正确的钥匙");
                        }
                        if (timer != null) {
                            timer.cancel();
                        }
                        timer.cancel();
                        myKey = null;
                        mlock();
                        return;
                    } else {
                        DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).updateKeyState("1", myKey);
                        openKeys.remove(myKey);
                        success = false;
                        if (openKeys.size() > 0) {
                            if (timer != null) {
                                timer.cancel();
                            }
                            myKey = null;
                            mlock();
                            return;
                        } else {
                            outTime = System.currentTimeMillis();
                            if (timer != null) {
                                timer.cancel();
                            }
                            timer.cancel();
                            speak("操作成功");
                            setEnable(true);
                            hidiDialog();
                            OttoManager.getInstance().deliverMsg(OttoMsg.OTTO_TO_HOME, null);
                            return;
                        }
                    }
                } else if (TextUtils.equals(mlockState, "03")) {
                    isFinish = false;
                    if (timer != null) {
                        timer.cancel();
                    }
                    speak("锁位损坏开锁失败");
                    hidiDialog();
                    success = false;
                    return;
                } else if (TextUtils.equals(mlockState, "02")) {
                    if (success) {
                        speak("请关闭柜门");
                        if (timer != null) {
                            timer.cancel();
                        }
                        timer.cancel();
                        myKey = null;
                        mlock();
                        return;
                    }
                }
            }
        };
        timer.start();
    }

    @UiThread
    public void hidiDialog() {
        dismiss();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isFinish = true;
        isDoing = false;
        listKeys.clear();
        openKeys.clear();
        keylock.clear();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        myKey = null;
        success = false;
    }

    public void speak(String s) {
        Speaker_.getInstance_(GoodBoxManagerApp_.getInstance()).speak(s);
    }
}